package com.enki.cigarettes.controller;

import com.alibaba.fastjson.JSONObject;
import com.enki.cigarettes.entity.AccessTokenT;
import com.enki.cigarettes.entity.UserT;
import com.enki.cigarettes.handler.Response;
import com.enki.cigarettes.repository.UserTRepository;
import com.enki.cigarettes.statics.StaticKeys;
import com.enki.cigarettes.utils.FileUtils;
import com.enki.cigarettes.utils.qiniu.QiNiuConfig;
import com.enki.cigarettes.utils.qiniu.QiNiuUtils;
import com.enki.cigarettes.utils.wechat.WechatUtil;
import com.qiniu.util.Auth;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import javax.servlet.http.HttpSession;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @author WCS.Wang
 * @version V1.0
 * @Package com.enki.cigarettes.controller
 * @Name e-cigarettes-shop-api-module
 * @Description: TODO 其他接口
 * @date 2019-07-19
 */
@RestController
@RequestMapping("/api/others")
@Slf4j
public class OthersController {


    @Autowired
    private QiNiuConfig qiNiuConfig;
    @Autowired
    UserTRepository userTRepository;


    @ApiOperation(value = "获取七牛上传凭证")
    @GetMapping(value = "/token")
    public Object getQiNiuUpToken() {
        Map<String, Object> responseData = new HashMap<>();
        String token = Auth.create(qiNiuConfig.getAccesskey(), qiNiuConfig.getSecretkey()).uploadToken(qiNiuConfig.getBucketname());
        responseData.put("uptoken", token);
        responseData.put("qiniuimghost", qiNiuConfig.getQiniuimghost());
        return Response.successToken(responseData, StaticKeys.SUCCESS);
    }

    @ApiOperation(value = "获取二维码")
    @GetMapping(value = "/qrcode")
    public Object qrCode(HttpSession session) {
        try {
            Object sessionId = session.getAttribute(StaticKeys.USER_ID);
            if (sessionId == null) {
                return Response.unauthorized_401("登录身份失效，请重新登录");
            }
            UserT userBean = userTRepository.findOneById(sessionId.toString());
            if (userBean == null) {
                return Response.unauthorized_401("登录身份失效，请重新登录");
            }
            AccessTokenT accessToken = WechatUtil.getAccessToken();
            if(accessToken == null) {
                return Response.badRequest_400("获取分享信息失败");
            }
            // 组装请求信息
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("scene",userBean.getInvitationCode());
            jsonObject.put("page","pages/index/index");
            jsonObject.put("width",430);
            jsonObject.put("auto_color", false);

            String requestUrl = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken.getAccessToken();
            InputStream inputStream = null;
            OutputStream outputStream = null;
            try {
                HttpClient client=new DefaultHttpClient();
                HttpPost post=new HttpPost(requestUrl);
                post.setHeader("Content-Type","application/json");
                StringEntity stringEntity=new StringEntity(jsonObject.toString(),"utf-8");
                stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
                post.setEntity(stringEntity);
                HttpResponse httpResponse=client.execute(post);
                inputStream=httpResponse.getEntity().getContent();
                String realpath = FileUtils.isExistDir();
                SimpleDateFormat sDateFormat;
                Random r = new Random();
                int rannum = (int) (r.nextDouble() * (99999 - 1000 + 1)) + 10000;
                sDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                String nowTimeStr = sDateFormat.format(new Date());
                String newFileFullname = nowTimeStr + rannum;
                //文件的保存地址
                String filePath = realpath + newFileFullname + ".png";
                File file = new File(filePath);
                if (!file.exists()) {
                    file.createNewFile();
                }
                outputStream = new FileOutputStream(file);
                int len = 0;
                byte[] buf = new byte[1024];
                while ((len = inputStream.read(buf, 0, 1024)) != -1) {
                    outputStream.write(buf, 0, len);
                }
                outputStream.flush();
//                String cloudFileKey = realpath + newFileFullname + ".png";// 云上的文件名称
//                cloudFileKey = cloudFileKey.replace('\\', '/');
//                QiNiuUtils.uploadFile(cloudFileKey, newFileFullname + ".png");
//                String qrCodeUrl = qiNiuConfig.getImghost() + newFileFullname + ".png";
                String qrCodeUrl = "https://www.enkivapor.com.cn" + File.separator + "qrcode" + File.separator + newFileFullname + ".png";
                log.info("qrCodeUrl：" + qrCodeUrl);
                return Response.success(qrCodeUrl, StaticKeys.SUCCESS);
            } catch (IOException e) {

            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (outputStream != null) {
                    try {
                        outputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return Response.success();
        } catch (Exception e) {
            log.error("获取分享二维码失败：" + e.getMessage());
            e.printStackTrace();
            return Response.serverError_500("获取分享二维码失败");
        }
    }

}
